package ks2;

import java.util.*;

public class AddMat {
	public static void main(String[] args) {
		int n = 1;
		while (n == 1) {
			Scanner scan = new Scanner(System.in);
			int muA, nuA, tuA, muB, nuB, tuB;
			System.out.println("请输入A矩阵的行，列，非零元的个数：");
			muA = scan.nextInt();
			nuA = scan.nextInt();
			tuA = scan.nextInt();
			System.out.println("请输入B矩阵的行，列，非零元的个数：");
			muB = scan.nextInt();
			nuB = scan.nextInt();
			tuB = scan.nextInt();
			if (muA != muB || nuA != nuB) {
				System.out.println("这两个矩阵行列数不相同，故不能相加，请重新输入！");
			} else {
				n = 2;
				Mat A = new Mat(muA, nuA, tuA);
				Mat B = new Mat(muB, nuB, tuB);

				System.out.println("请输入A矩阵的三元组：");
				for (int i = 1; i <= tuA; i++) {
					A.data[i].row = scan.nextInt();
					A.data[i].col = scan.nextInt();
					A.data[i].v = scan.nextInt();
				}
				System.out.println("A矩阵为：");
				A.display();

				System.out.println("请输入B矩阵的三元组：");
				for (int i = 1; i <= tuB; i++) {
					B.data[i].row = scan.nextInt();
					B.data[i].col = scan.nextInt();
					B.data[i].v = scan.nextInt();
				}
				System.out.println("B矩阵为：");
				B.display();
				Mat C = new Mat(muA, nuA, 1);
				Mat D = new Mat(muA, nuA, 1);
				add(A, B, C, D);
				System.out.println("相加后的矩阵C为：");
				C.display();
				System.out.println("转置后的矩阵D为：");
				D.display();
			}
		}
	}

	public static void add(Mat A, Mat B, Mat C, Mat D) {
		int k, l, temp;
		k = 1;
		l = 1;
		while (k <= A.tu && l <= B.tu) {
			if ((A.data[k].row == B.data[l].row) && (A.data[k].col == B.data[l].col)) {
				temp = A.data[k].v + B.data[l].v;
				if (temp != 0) {
					C.data[C.tu].row = A.data[k].row;
					C.data[C.tu].col = A.data[k].col;
					C.data[C.tu].v = temp;
					C.tu++;
					D.data[D.tu].row = A.data[k].col;
					D.data[D.tu].col = A.data[k].row;
					D.data[D.tu].v = temp;
					D.tu++;
					A.data[k].v = 0;
					B.data[l].v = 0;
				}
				k++;
				l++;
			} else if (A.data[k].v != 0) {
				if (B.data[k].v != 0) {
					C.data[C.tu].row = B.data[l].row;
					C.data[C.tu].col = B.data[l].col;
					C.data[C.tu].v = B.data[l].v;
					C.tu++;
					D.data[D.tu].row = B.data[l].col;
					D.data[D.tu].col = B.data[l].row;
					D.data[D.tu].v = B.data[l].v;
					D.tu++;
					B.data[l].v = 0;
					l++;

				}
				C.data[C.tu].row = A.data[k].row;
				C.data[C.tu].col = A.data[k].col;
				C.data[C.tu].v = A.data[k].v;
				C.tu++;
				D.data[D.tu].row = A.data[k].col;
				D.data[D.tu].col = A.data[k].row;
				D.data[D.tu].v = A.data[k].v;
				D.tu++;
				A.data[k].v = 0;
				k++;

			} else {
				k++;
				l++;
			}
		}
	}
}
